/*
 * Created by IntelliJ IDEA.
 * User: amrk
 * Date: 23/02/2004
 * Time: 21:43:04
 */
package com.talios.jira.settings;

import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogBuilder;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.IconLoader;
import com.talios.jira.browser.JiraProjectDetails;
import com.talios.jira.browser.signals.JiraServerDetails;
import com.talios.jira.settings.projects.ProjectSettings;
import com.talios.jira.settings.projects.SettingsFactory;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;

public class ServerDetails {
    private JButton add;
    private JButton cancel;
    private JTable projects;
    private JPasswordField password;
    private JCheckBox useCustomDateFormat;
    private JTextField customDateFormat;
    //    private JCheckBox validateRssFeeds;
    private JTextField userName;
    private JTextField baseUrl;
    private JPanel mainPanel;
    private JiraServerDetails server;
    private DialogWrapper dialog;
    private ProjectListTableModel projectListModel;
    private JPanel projectToolBar;
    private Project project;

    public ServerDetails(Project project, String title) {
        this.project = project;
        DialogBuilder db = new DialogBuilder(project);
        dialog = db.getDialogWrapper();
        dialog.setModal(true);
        dialog.setTitle(title);
        dialog.getContentPane().add(mainPanel);
        dialog.setSize(550, 350);
        add.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                applyServerSettings();
                dialog.close(0);
            }
        });
        cancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dialog.close(-1);
            }
        });
        projects.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent mouseEvent) {
                if (mouseEvent.getClickCount() == 2 && mouseEvent.getButton() == MouseEvent.BUTTON1) {
                    new EditProjectAction().actionPerformed(null);
                }
            }
        });
        useCustomDateFormat.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent event) {
                boolean b = event.getStateChange() == ItemEvent.SELECTED;
                customDateFormat.setEnabled(b);
            }
        });
        ActionManager actionManager = ActionManager.getInstance();
        DefaultActionGroup viewGroup = new DefaultActionGroup();
        viewGroup.add(new ServerDetails.AddProjectAction());
        viewGroup.add(new ServerDetails.RemoveProjectAction());
        ActionToolbar viewToolbar = actionManager.createActionToolbar("JIRA.ProjectToolbar", viewGroup, false);
        JComponent component = viewToolbar.getComponent();
        projectToolBar.add(component);
    }

    private void applyServerSettings() {
        server.setBaseurl(baseUrl.getText());
        server.setUsername(userName.getText());
        server.setPassword(new String(password.getPassword()));
        server.setUseCustomDateFormat(useCustomDateFormat.isSelected());
        server.setCustomDateFormat(customDateFormat.getText());
    }

    public JiraServerDetails editServerDetails(JiraServerDetails server) {
        this.server = server;
        setData(server);
        customDateFormat.setEnabled(server.getUseCustomDateFormat());
        projectListModel = new ProjectListTableModel(server);
        projects.setModel(projectListModel);
        dialog.show();
        if (dialog.getExitCode() != -1) {
            getData(server);
            return server;
        } else {
            return null;
        }
    }

    public void setData(JiraServerDetails data) {
        baseUrl.setText(data.getBaseurl());
        userName.setText(data.getUsername());
        customDateFormat.setText(data.getCustomDateFormat());
        useCustomDateFormat.setSelected(data.getUseCustomDateFormat());
        password.setText(data.getPassword());
    }

    public void getData(JiraServerDetails data) {
        data.setBaseurl(baseUrl.getText());
        data.setUsername(userName.getText());
        data.setCustomDateFormat(customDateFormat.getText());
        data.setUseCustomDateFormat(useCustomDateFormat.isSelected());
        data.setPassword(new String(password.getPassword()));
    }

    public boolean isModified(JiraServerDetails data) {
        if (baseUrl.getText() != null ? !baseUrl.getText().equals(data.getBaseurl()) : data.getBaseurl() != null)
            return true;
        if (userName.getText() != null ? !userName.getText().equals(data.getUsername()) : data.getUsername() != null)
            return true;
        if (customDateFormat.getText() != null ? !customDateFormat.getText().equals(data.getCustomDateFormat()) : data.getCustomDateFormat() != null)
            return true;
        if (useCustomDateFormat.isSelected() != data.getUseCustomDateFormat()) return true;
        return password.getText() != null ? !password.getText().equals(data.getPassword()) : data.getPassword() != null;
    }

    public class ProjectListTableModel extends AbstractTableModel {
        private List projectList;
        private JiraServerDetails server;

        public ProjectListTableModel(JiraServerDetails server) {
            this.server = server;
            projectList = new ArrayList();
            if (server != null) {
                projectList = server.getProjectList();
            }
        }

        public int getColumnCount() {
            return 4;
        }

        public int getRowCount() {
            return projectList == null ? 0 : projectList.size();
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            JiraProjectDetails project = (JiraProjectDetails) projectList.get(rowIndex);
            if (project != null) {
                switch (columnIndex) {
                    case 0:
                        return project.getProjectId();
                    case 1:
                        return project.getProjectKey();
                    case 2:
                        return project.getProjectName();
                    case 3:
                        return project.getComponentName();
                    default:
                        return "ERR";
                }
            } else {
                return "ERR";
            }
        }

        public String getColumnName(int column) {
            switch (column) {
                case 0:
                    return "ID";
                case 1:
                    return "Key";
                case 2:
                    return "Title";
                case 3:
                    return "Component";
                default:
                    return "ERR";
            }
        }

        public JiraProjectDetails getProject(int selectedRow) {
            if (selectedRow != -1) {
                JiraProjectDetails projectDetails = (JiraProjectDetails) projectList.get(selectedRow);
                return projectDetails;
            } else {
                return null;
            }
        }
    }

    private class AddProjectAction extends AnAction {
        public AddProjectAction() {
            super("Add", "Add Project", IconLoader.getIcon("/general/add.png"));
        }

        public void actionPerformed(AnActionEvent event) {
            applyServerSettings();
            JiraProjectDetails jiraProject = new JiraProjectDetails(server);
            ProjectSettings projectSettings = SettingsFactory.getInstance().getSettingsEditorForProject(jiraProject, "Add Project");
            if (projectSettings.editProject(ServerDetails.this.dialog)) {
                ServerDetails.this.server.getProjectList().add(jiraProject);
                ServerDetails.this.projectListModel.fireTableDataChanged();
            }
        }
    }

    private class EditProjectAction extends AnAction {
        public EditProjectAction() {
            super("Edit", "Edit Project", IconLoader.getIcon("/general/configurableEditor.png"));
        }

        public void actionPerformed(AnActionEvent event) {
            ProjectListTableModel projectsModel = (ProjectListTableModel) ServerDetails.this.projects.getModel();
            JiraProjectDetails project = projectsModel.getProject(ServerDetails.this.projects.getSelectedRow());
            ProjectSettings projectSettings = SettingsFactory.getInstance().getSettingsEditorForProject(project, "Edit Project");
            if (projectSettings.editProject(ServerDetails.this.dialog)) {
                projectsModel.fireTableDataChanged();
            }
        }
    }

    private class RemoveProjectAction extends AnAction {
        public RemoveProjectAction() {
            super("Remove", "Remove Project", IconLoader.getIcon("/general/remove.png"));
        }

        public void actionPerformed(AnActionEvent event) {
            if (Messages.showYesNoDialog(project, "Remove Selected Project?", "JIRA", IconLoader.getIcon("/general/remove.png")) == JOptionPane.YES_OPTION) {
                ProjectListTableModel projectsModel = (ProjectListTableModel) ServerDetails.this.projects.getModel();
                JiraProjectDetails project = projectsModel.getProject(ServerDetails.this.projects.getSelectedRow());
                ServerDetails.this.server.getProjectList().remove(project);
                ServerDetails.this.projectListModel.fireTableDataChanged();
            }
        }

        public void update(AnActionEvent event) {
            event.getPresentation().setEnabled(projects.getSelectedRowCount() != 0);
        }
    }
}